<template>
  <div class="todoapp">
    <todo-header :list="list" @add="add" @checkChange="list.forEach(v => v.isDone = $event)"/>
    <todo-main :list="selList" @del="del"/>
    <todo-footer @clear="list = list.filter(v => v.isDone === false)" :list="list" @change="status = $event"/>
  </div>
</template>

<script>
// 导入组件
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  // 注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data () {
    return {
      list: JSON.parse( localStorage.getItem('todos97') ) || [
        { id: 100, name: '吃饭', isDone: true },
        { id: 201, name: '睡觉', isDone: false },
        { id: 103, name: '打豆豆', isDone: true }
      ],
      status: '全部'
    }
  },
  beforeMount () {
    console.log('beforeMount', document.querySelector('.header'))
  },
  mounted () {
    console.log('mounted', document.querySelector('.header'))

  },
  methods: {
    del (id) {
      // 根据id删除，所谓删除就是筛选出除了这s个id以外的别的数据
      this.list = this.list.filter(v => v.id !== id)
    },
    add (task) {
      this.list.push({
        // 时间戳作为id肯定不重复
        id: Date.now(),
        name: task,
        isDone: false
      })
    }
  },

  computed: {
    selList () {
      if (this.status === '未完成') {
        // 筛选出未完成，也就是isDone为false
        return this.list.filter(v => v.isDone === false)

      }else if(this.status === '已完成') {
        // 筛选出已完成，也就是isDone为true
        return this.list.filter(v => v.isDone === true)
        
      }else {
        return this.list
      }
    }
  },

  watch: {
    list: {
      deep: true,
      handler () {
        localStorage.setItem('todos97', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
